package com.xiake.app.web.controller.user;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiake.core.annotation.LoginUser;
import com.xiake.core.annotation.UserNeedLogin;
import com.xiake.core.constants.SMSCodeConstants;
import com.xiake.core.entity.user.SmsAuth;
import com.xiake.core.entity.user.UserInfo;
import com.xiake.core.entity.user.UserSession;
import com.xiake.core.model.AppUserInfo;
import com.xiake.core.model.ReturnDataModel;
import com.xiake.service.user.SmsAuthService;
import com.xiake.service.user.UserInfoService;
import com.xiake.service.user.UserSessionService;
import com.xiake.utils.Base64Utils;
import com.xiake.utils.DateUtils;
import com.xiake.utils.SMSUtil;

@Controller
@RequestMapping("user")
public class UserInfoController {
  @Autowired
  private UserInfoService userInfoService;

  @Autowired
  private UserSessionService userSessionService;

  @Autowired
  private SmsAuthService smsAuthService;

  private static Logger log = LoggerFactory.getLogger(UserInfoController.class);

  @RequestMapping("index")
  @ResponseBody
  public ReturnDataModel index() throws Exception {
    UserInfo user = new UserInfo();
    user.setId(5);
    user.setPhone("18600441895");
    user.setSchoolName("渝工学院");
    user.setGender(1);
    user.setNickname("龙");
    userInfoService.save(user);
    log.error(" 看到这个就成功了");
    return new ReturnDataModel(1, "看到这个就成功了");
  }

  @RequestMapping("login")
  @ResponseBody
  public ReturnDataModel login(String phone, String password, String code) throws Exception {
    ReturnDataModel rdm = new ReturnDataModel(ReturnDataModel.RETURN_SUCCESS, "登陆成功");
    Map<String, Object> sqlMap = new HashMap<String, Object>();
    sqlMap.put("phone", phone);
    sqlMap.put("password", Base64Utils.md5AndEncode(password));
    UserInfo userInfo = userInfoService.get(sqlMap, "ForLogin");
    if (userInfo == null) {
      rdm.setStatus(ReturnDataModel.RETURN_FAILURE);
      rdm.setMsg("用户名或密码错误!");
      return rdm;
    } else if (userInfo.getStatus().intValue() == 1) {
      rdm.setStatus(ReturnDataModel.RETURN_FAILURE);
      rdm.setMsg("您的账户已被屏蔽!");
      return rdm;
    }
    String token = generateSessionAndSave(userInfo.getId());
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("token", token);
    rdm.setData(data);
    return rdm;
  }

  @RequestMapping("get-user-info")
  @ResponseBody
  public ReturnDataModel getUserInfo(@LoginUser AppUserInfo userInfo) throws Exception {
    ReturnDataModel rdm = new ReturnDataModel(ReturnDataModel.RETURN_SUCCESS, "获取成功");

    if (userInfo.getStatus().intValue() == 1) {
      rdm.setStatus(ReturnDataModel.RETURN_FAILURE);
      rdm.setMsg("您的账户已被屏蔽!");
      return rdm;
    }
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("userInfo", userInfo);
    rdm.setData(data);
    return rdm;
  }

  @RequestMapping("register")
  @ResponseBody
  public ReturnDataModel register(String phone, String password, String code) throws Exception {
    ReturnDataModel rdm = new ReturnDataModel(ReturnDataModel.RETURN_SUCCESS, "注册成功");
    if (StringUtils.isBlank(phone) || StringUtils.isBlank(password) || StringUtils.isBlank(code)) {
      rdm.setStatus(ReturnDataModel.RETURN_FAILURE);
      rdm.setMsg("请完整填写相关信息!");
      return rdm;
    }
    Map<String, Object> sqlMap = new HashMap<String, Object>();
    sqlMap.put("type", SMSCodeConstants.USER_REGISTER);
    sqlMap.put("code", code);
    sqlMap.put("phone", phone);
    SmsAuth smsAuth = smsAuthService.get(sqlMap, "ByCode");
    if (smsAuth == null) {
      rdm.setStatus(ReturnDataModel.RETURN_FAILURE);
      rdm.setMsg("您的验证码已过期，请重新获取!");
      return rdm;
    }
    UserInfo userInfo = new UserInfo();
    userInfo.setPhone(phone);
    userInfo.setPassword(Base64Utils.md5AndEncode(password));
    userInfoService.save(userInfo);
    String token = generateSessionAndSave(userInfo.getId());
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("token", token);
    rdm.setData(data);
    return rdm;

  }

  @RequestMapping("send-code")
  @ResponseBody
  public ReturnDataModel sendCode(String phone, Integer type) throws Exception {
    ReturnDataModel rdm = new ReturnDataModel(ReturnDataModel.RETURN_SUCCESS, "发送成功");
    String code = SMSCodeConstants.getCode() + "";
    String content = SMSCodeConstants.SMS_HEAD + code + SMSCodeConstants.getFoot(type);
    SmsAuth sms = new SmsAuth();
    sms.setPhone(phone);
    sms.setContent(content);
    sms.setType(type);
    sms.setCode(code);
    String result = SMSUtil.send(phone, content);
    sms.setThirdResult(result);
    smsAuthService.save(sms);
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("code", code);
    rdm.setData(data);
    return rdm;
  }

  @RequestMapping("update")
  @ResponseBody
  @UserNeedLogin
  public ReturnDataModel update(@LoginUser AppUserInfo appUser, String nickname, Integer gender,
      String schoolName, String sign, String headImg) throws Exception {
    ReturnDataModel rdm = new ReturnDataModel(ReturnDataModel.RETURN_SUCCESS, "修改成功");
    UserInfo userInfo = new UserInfo();
    userInfo.setId(appUser.getId());
    userInfo.setNickname(nickname);
    userInfo.setGender(gender);
    userInfo.setSchoolName(schoolName);
    userInfo.setHeadImg(headImg);
    userInfoService.save(userInfo);
    return rdm;
  }

  private String generateSessionAndSave(Integer userId) throws Exception {
    String token = userId + DateUtils.getMillis(new Date()) + "";
    token = Base64Utils.md5AndEncode(token);
    UserSession session = new UserSession();
    session.setUserId(userId);
    session.setToken(token);
    userSessionService.save(session);
    return token;
  }

}
